import { Application } from 'egg';

export default (app: Application) => {
  const { controller, router } = app;
  // validator 
  app.validator.addRule('dateString',(_, value)=>{
    try {
      if ( /^(\+?0?86\-?)?1[3-9]\d{9}$/.test(value) ) throw Error;
    } catch (err) {
      return 'must be a Date String'
    }
  })
  app.validator.addRule('telephone',(_, value)=>{
    try {
      if ( Date.parse(value).toString() == 'Invalid Date' ) throw Error;
    } catch (err) {
      return 'must be a telephone String like +8617300000000'
    }
  })
  // middleware
  const loginCheck = app.middleware.loginCheck(undefined, app);
  // visitor router
  router.get('/', controller.home.index);
  // Articles
  router.get('/API/V1/articles', controller.articles.index);
  router.get('/API/V1/articles/:id', controller.articles.byId);
  // Categories
  router.get('/API/V1/categories', controller.categories.index);
  router.get('/API/V1/categories/statistics', controller.categories.statistics);
  // Admin Users
  router.post('/API/V1/admin/users/login', controller.admin.users.login);
  router.put('/API/V1/admin/users/:id', loginCheck, controller.admin.users.modifyPassword);
  // Admin Articles
  router.get('/API/V1/admin/articles', loginCheck, controller.articles.index);
  router.get('/API/V1/admin/articles/:id', loginCheck, controller.articles.byId);
  router.post('/API/V1/admin/articles', loginCheck, controller.articles.newArticle);
  router.put('/API/V1/admin/articles/:id', loginCheck, controller.articles.modify);
  router.delete('/API/V1/admin/articles/:id', loginCheck, controller.articles.deleteById);
  router.post('/API/V1/admin/articles/:id/images', loginCheck, controller.articles.uploadImage);
  //  Admin Categories
  router.post('/API/V1/admin/categories', loginCheck, controller.categories.add);
  router.delete("/API/V1/admin/categories/:id", loginCheck, controller.categories.deleteById);
  router.put("/API/V1/admin/categories/:id", loginCheck, controller.categories.rename);
  // Feedback
  router.post('/API/V1/feedbacks', app.controller.feedback.submit);
  // Admin Feedback
  router.delete('/API/V1/admin/feedbacks/:id', loginCheck , app.controller.feedback.delete);
  router.get('/API/V1/admin/feedbacks', loginCheck, controller.feedback.get);
};
